#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
日志工具模块
"""

import os
import logging
from pathlib import Path
from logging.handlers import RotatingFileHandler

# 日志目录
LOG_DIR = Path("./logs")

# 日志格式
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

# 日志级别映射
LOG_LEVELS = {
    "debug": logging.DEBUG,
    "info": logging.INFO,
    "warning": logging.WARNING,
    "error": logging.ERROR,
    "critical": logging.CRITICAL
}

def setup_logger(name, level="info", log_file=None):
    """
    设置并返回logger对象
    
    Args:
        name: 日志名称
        level: 日志级别
        log_file: 日志文件名，如果为None，将根据name自动生成
    
    Returns:
        logger对象
    """
    # 确保日志目录存在
    os.makedirs(LOG_DIR, exist_ok=True)
    
    # 确定日志级别
    log_level = LOG_LEVELS.get(level.lower(), logging.INFO)
    
    # 创建logger
    logger = logging.getLogger(name)
    logger.setLevel(log_level)
    
    # 防止重复添加handler
    if logger.handlers:
        return logger
    
    # 创建控制台handler
    console_handler = logging.StreamHandler()
    console_handler.setLevel(log_level)
    console_formatter = logging.Formatter(LOG_FORMAT)
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)
    
    # 如果指定了日志文件，创建文件handler
    if log_file is None:
        log_file = LOG_DIR / f"{name}.log"
    else:
        log_file = LOG_DIR / log_file
    
    file_handler = RotatingFileHandler(
        log_file, maxBytes=10*1024*1024, backupCount=5
    )
    file_handler.setLevel(log_level)
    file_formatter = logging.Formatter(LOG_FORMAT)
    file_handler.setFormatter(file_formatter)
    logger.addHandler(file_handler)
    
    return logger

def get_logger(name):
    """
    获取logger对象，如果不存在则创建
    
    Args:
        name: 日志名称
    
    Returns:
        logger对象
    """
    logger = logging.getLogger(name)
    if not logger.handlers:
        return setup_logger(name)
    return logger 
